package com.hailiao.beidou.message.ui.page.setting

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.d10ng.compose.model.UiViewModelManager
import com.d10ng.compose.ui.dialog.builder.ConfirmDialogBuilder
import com.d10ng.compose.ui.feedback.NotifyType
import com.d10ng.compose.ui.sheet.builder.RadioSheetBuilder
import com.hailiao.beidou.message.bd.Beidou
import com.hailiao.beidou.message.bd.constant.ProtoVersion
import com.hailiao.beidou.message.data.setting.SettingRepository
import com.hailiao.beidou.message.data.store.contant.CommunicationMode
import kotlinx.coroutines.launch

/**
 * 设置
 * @Author d10ng
 * @Date 2024/3/4 16:01
 */
class SettingScreenViewModel: ViewModel() {

    // 协议版本
    val protoFlow = SettingRepository.protoFlow
    // 通讯模式
    val commModeFlow = SettingRepository.commModeFlow

    /**
     * 点击协议
     */
    fun onClickProto() {
        if (Beidou.isConnected()) {
            UiViewModelManager.showNotify(NotifyType.Primary, "设备已连接，无法切换协议版本")
            return
        }
        UiViewModelManager.showSheet(RadioSheetBuilder(
            title = "协议版本切换",
            items = ProtoVersion.entries.toSet(),
            itemText = { it.text },
            selectedItem = protoFlow.value,
            showButton = false,
            onConfirmClick = {
                viewModelScope.launch { SettingRepository.setProto(it) }
                true
            }
        ))
    }

    /**
     * 点击通讯模式
     */
    fun onClickCommMode() {
        if (Beidou.isConnected()) {
            UiViewModelManager.showDialog(ConfirmDialogBuilder(
                content = "通讯线路切换将会断开当前设备连接，是否继续？",
                onConfirmClick = {
                    viewModelScope.launch {
                        showCommModeSheet()
                    }
                    true
                }
            ))
        } else {
            showCommModeSheet()
        }
    }

    /**
     * 显示通讯模式选择框
     */
    private fun showCommModeSheet() {
        UiViewModelManager.showSheet(RadioSheetBuilder(
            title = "通讯线路切换",
            items = CommunicationMode.entries.toSet(),
            itemText = { it.text },
            selectedItem = commModeFlow.value,
            showButton = false,
            onConfirmClick = {
                viewModelScope.launch { SettingRepository.setCommMode(it) }
                true
            }
        ))
    }
}